const mysql = require('mysql2');
const dbConfig = require('../config/database');

// 创建数据库连接
const connection = mysql.createConnection(dbConfig);

connection.connect((err) => {
    if (err) {
        console.error('数据库连接失败: ' + err.stack);
        return;
    }
    console.log('已连接到数据库');
});

// 查找用户
function findUserByUsername(username, callback) {
    const query = 'SELECT * FROM users WHERE username = ?';
    connection.query(query, [username], (error, results) => {
        if (typeof callback !== 'function') {
            console.error('Callback is not a function in findUserByUsername.');
            if (error) {
                console.error('Database error occurred:', error);
            } else {
                console.error('findUserByUsername called without a valid callback function.');
            }
            return;
        }

        if (error) {
            return callback(error, null);
        }

        callback(null, results[0]);
    });
}

// 创建用户
function createUser(username, password, callback) {
    const query = 'INSERT INTO users (username, password) VALUES (?, ?)';
    connection.query(query, [username, password], (error, results) => {
        if (typeof callback !== 'function') {
            console.error('Callback is not a function in createUser.');
            if (error) {
                console.error('Database error occurred:', error);
            } else {
                console.error('createUser called without a valid callback function.');
            }
            return;
        }

        if (error) {
            return callback(error, null);
        }

        callback(null, results);
    });
}

module.exports = {
    findUserByUsername,
    createUser
};